﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ServiceStack.Mvc;
using IAS.WEB.ViewModels;
using ServiceStack.Auth;
using ServiceStack;
using ServiceStack.OrmLite;
using System.Web.Security;
namespace IAS.WEB.Areas.Account.Controllers
{
    public class LoginController : ServiceStackController
    {
        public HomeViewModel GetViewModel()
        {
            var response = new HomeViewModel { Session = SessionAs<AuthUserSession>() };
            if (response.Session.UserAuthId != null)
            {
                var userAuthId = int.Parse(response.Session.UserAuthId);
                response.UserAuths = Db.Select<UserAuth>(x => x.Id == userAuthId);
                response.UserAuthDetails = Db.Select<UserAuthDetails>(x => x.UserAuthId == userAuthId);
            }
            return response;
        }

        // GET: Login
        public ActionResult Index()
        {
            return View(GetViewModel());
        }

        public ActionResult Login(string userName, string passWord, bool? rememberMe, string redirect)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    using (var authService = ResolveService<AuthenticateService>())
                    {                        
                        var response = authService.Authenticate(new Authenticate
                        {
                            provider = CredentialsAuthProvider.Name,
                            UserName = userName,
                            Password = passWord,
                            RememberMe = rememberMe,
                        });
                        
                        // add ASP.NET auth cookie
                        FormsAuthentication.SetAuthCookie(userName, true);

                        return Redirect(string.IsNullOrEmpty(redirect) ? "/" : redirect);
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
            }
            return View("Index", GetViewModel());
        }

        public ActionResult Logout()
        {
            Execute(new Authenticate { provider = "logout" });
            FormsAuthentication.SignOut();

            return Redirect("/");
        }
    }
}